package com.herench.bunch.clinic.convert;

import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.model.v24.datatype.CE;
import ca.uhn.hl7v2.model.v24.group.RTB_K13_ROW_DEFINITION;
import ca.uhn.hl7v2.model.v24.message.QBP_Q11;
import ca.uhn.hl7v2.model.v24.message.RTB_K13;
import ca.uhn.hl7v2.model.v24.segment.MSA;
import ca.uhn.hl7v2.model.v24.segment.MSH;
import ca.uhn.hl7v2.model.v24.segment.QPD;
import ca.uhn.hl7v2.model.v24.segment.RDT;
import ca.uhn.hl7v2.parser.DefaultModelClassFactory;
import com.herench.bunch.clinic.handler.ProxyMsgCodeConstant;
import com.herench.bunch.clinic.support.ProxyMsgTemplate;
import com.herench.bunch.commons.support.RequestMessage;
import com.herench.bunch.commons.utils.IdGenerator;
import org.dom4j.Document;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.util.Assert;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.*;

@Configuration
@PropertySource("classpath:config.properties")
public class DeptListOfClinicConvert extends AbstractMessageConvert {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${deptNo}")
    private  String deptNo;

    @Autowired
    private Environment environment;

    @Override
    public Document doToMessage(RequestMessage requestMessage) throws Exception {
        String res = ProxyMsgTemplate.getInMsgTpl(ProxyMsgCodeConstant.DEPT_LIST_TRADE_CODE).asXML();
        logger.info(requestMessage.getMsgCode() + " to HIS XML = "+ res);
        return ProxyMsgTemplate.getInMsgTpl(ProxyMsgCodeConstant.DEPT_LIST_TRADE_CODE);
    }

    public Message doFromMessage(String message) throws Exception {
        Assert.notNull(message, "message 为空");
        Document doc = ProxyMsgTemplate.getOutMsgTpl(message);
        RTB_K13 rtbK13 = new RTB_K13();
        rtbK13.initQuickstart("RTB_K13", "RTB_K13", "P");
        MSH msh = rtbK13.getMSH();
        initResponseMessageMSH(msh);

        MSA msa = rtbK13.getMSA();
        msa.getErrorCondition().getCe1_Identifier().setValue(doc.getRootElement().elementTextTrim("IsSuccessed"));
        msa.getErrorCondition().getCe2_Text().setValue(doc.getRootElement().elementTextTrim("ErrorMsg"));

        RTB_K13_ROW_DEFINITION definition = rtbK13.getROW_DEFINITION();
        Element items = doc.getRootElement().element("Items");
        String fileName = this.getClass().getClassLoader().getResource("config.properties").getPath();
        Properties prop = new Properties();
        InputStream in = new BufferedInputStream(new FileInputStream(fileName));
        prop.load(in);     ///加载属性列表
        String deptNo =prop.getProperty("deptNo");

        List res = Arrays.asList(deptNo.split("#"));
        Boolean flag;

        int index = 0;
        for (Iterator<Element> iterator = items.elementIterator(); iterator.hasNext(); ) {
            Element el = iterator.next();
            String deptCode = el.elementTextTrim("DeptCode");

            flag = res.contains(deptCode);

            if(flag){
//            if (deptCode.equals("01010201") || deptCode.equals("01010203") || deptCode.equals("01010205") || deptCode.equals("01010207") || deptCode.equals("0101020A") || deptCode.equals("0101020C") || deptCode.equals("0101020E") || deptCode.equals("0101020G") || deptCode.equals("0101020H") || deptCode.equals("0101020I") || deptCode.equals("0101020J") || deptCode.equals("0101020L01") || deptCode.equals("0101020M") || deptCode.equals("0101020N") || deptCode.equals("01010209")) {
                RDT rdt = new RDT(rtbK13, new DefaultModelClassFactory());
                CE ce = new CE(rtbK13);
                ce.getCe1_Identifier().setValue("RD");
                StringBuffer buffer = new StringBuffer();
                buffer.append("DeptCode=").append(el.elementTextTrim("DeptCode")).append("#")
                        .append("DeptName=").append(el.elementTextTrim("DeptName")).append("#")
                        .append("DeptDesc=").append(el.elementTextTrim("DeptDesc")).append("#")
                        .append("ParentCode=").append(el.elementTextTrim("ParentCode")).append("#")
                        .append("OrderNum=").append(el.elementTextTrim("OrderNum")).append("#")
                        .append("DeptType=").append(el.elementTextTrim("DeptType")).append("#")
                        .append("DeptAddress=").append(el.elementTextTrim("DeptAddress")).append("#")
                        .append("branchCode=").append(el.elementTextTrim("")).append("#")
                        .append("IsEnabled=").append(el.elementTextTrim("IsEnabled"));
                ce.getCe2_Text().setValue(buffer.toString());
                rdt.getColumnValue().setData(ce);
                definition.insertRDT(rdt, index++);
            }
        }
        return rtbK13;
    }

    @Override
    public Message generatorReqMessage() throws Exception {
        QBP_Q11 qbp = new QBP_Q11();
        qbp.initQuickstart("QBP_Q11", "Q11", "L");
        MSH msh = qbp.getMSH();
        msh.getMsh3_SendingApplication().getHd1_NamespaceID().setValue("SSM");
        msh.getMessageControlID().setValue(IdGenerator.getUUID());
        msh.getMsh11_ProcessingID().getPt1_ProcessingID().setValue("200010");
        msh.getMsh11_ProcessingID().getProcessingMode().setValue("QR");
        QPD qpd = qbp.getQPD();
        qpd.getMessageQueryName().getIdentifier().setValue("查询科室列表");
        qpd.getQpd2_QueryTag().setValue("QR");
        return qbp;
    }
}
